package ch.fhnw.edu.rental.daos.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import ch.fhnw.edu.rental.daos.RentalDAO;
import ch.fhnw.edu.rental.model.Rental;
import ch.fhnw.edu.rental.model.User;

public class JpaRentalDAO implements RentalDAO, ManagedDAO<Rental> {

	@PersistenceContext
	private EntityManager em;
	
	@Override
	public Rental getById(Long id) {
		return this.em.find(Rental.class, id);
	}

	@Override
	public List<Rental> getAll() {
		Query q = this.em.createQuery("from Rental m");
		return q.getResultList();
	}

	@Override
	public List<Rental> getRentalsByUser(User user) {
		return user.getRentals();
	}

	@Override
	public void saveOrUpdate(Rental rental) {
		if (null == rental.getId()) {
			this.em.persist(rental);
		} else {
			this.em.merge(rental);
		}
	}

	@Override
	public void delete(Rental rental) {
		this.em.remove(rental);
	}

	@Override
	public Rental manage(Rental instance) {
		return em.merge(instance);
	}
}
